﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
namespace Admin.NET.Application;

/// <summary>
/// 供应商表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class SyssupplierService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Syssupplier> _syssupplierRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public SyssupplierService(SqlSugarRepository<Syssupplier> syssupplierRep, ISqlSugarClient sqlSugarClient)
    {
        _syssupplierRep = syssupplierRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询供应商表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询供应商表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<SyssupplierOutput>> Page(PageSyssupplierInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _syssupplierRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Code.Contains(input.Keyword) || u.Name.Contains(input.Keyword) || u.Industry.Contains(input.Keyword) || u.Category.Contains(input.Keyword) || u.ContactPerson.Contains(input.Keyword) || u.ContactPhone.Contains(input.Keyword) || u.Email.Contains(input.Keyword) || u.PurchasingDepartment.Contains(input.Keyword) || u.PurchasingManager.Contains(input.Keyword) || u.Address.Contains(input.Keyword) || u.Remarks.Contains(input.Keyword) || u.AccountName.Contains(input.Keyword) || u.TaxpayerId.Contains(input.Keyword) || u.BankAccount.Contains(input.Keyword) || u.OpeningBank.Contains(input.Keyword) || u.OpeningBankAddress.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Industry), u => u.Industry.Contains(input.Industry.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Category), u => u.Category.Contains(input.Category.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ContactPerson), u => u.ContactPerson.Contains(input.ContactPerson.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ContactPhone), u => u.ContactPhone.Contains(input.ContactPhone.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Email), u => u.Email.Contains(input.Email.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PurchasingDepartment), u => u.PurchasingDepartment.Contains(input.PurchasingDepartment.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PurchasingManager), u => u.PurchasingManager.Contains(input.PurchasingManager.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Address), u => u.Address.Contains(input.Address.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remarks), u => u.Remarks.Contains(input.Remarks.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.AccountName), u => u.AccountName.Contains(input.AccountName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TaxpayerId), u => u.TaxpayerId.Contains(input.TaxpayerId.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.BankAccount), u => u.BankAccount.Contains(input.BankAccount.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OpeningBank), u => u.OpeningBank.Contains(input.OpeningBank.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OpeningBankAddress), u => u.OpeningBankAddress.Contains(input.OpeningBankAddress.Trim()))
            .WhereIF(input.PurchasingDepartmentId != null, u => u.PurchasingDepartmentId == input.PurchasingDepartmentId)
            .WhereIF(input.PurchasingManagerId != null, u => u.PurchasingManagerId == input.PurchasingManagerId)
            .WhereIF(input.Status != null, u => u.Status == input.Status)
            .WhereIF(input.DeleteTimeRange?.Length == 2, u => u.DeleteTime >= input.DeleteTimeRange[0] && u.DeleteTime <= input.DeleteTimeRange[1])
            .Select<SyssupplierOutput>();
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取供应商表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取供应商表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Syssupplier> Detail([FromQuery] QueryByIdSyssupplierInput input)
    {
        return await _syssupplierRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加供应商表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加供应商表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddSyssupplierInput input)
    {
        var entity = input.Adapt<Syssupplier>();
        return await _syssupplierRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新供应商表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新供应商表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateSyssupplierInput input)
    {
        var entity = input.Adapt<Syssupplier>();
        await _syssupplierRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除供应商表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除供应商表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteSyssupplierInput input)
    {
        var entity = await _syssupplierRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _syssupplierRep.FakeDeleteAsync(entity);   //假删除
        //await _syssupplierRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除供应商表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除供应商表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteSyssupplierInput> input)
    {
        var exp = Expressionable.Create<Syssupplier>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _syssupplierRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _syssupplierRep.FakeDeleteAsync(list);   //假删除
        //return await _syssupplierRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 导出供应商表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出供应商表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageSyssupplierInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportSyssupplierOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "供应商表导出记录");
    }
    
    /// <summary>
    /// 下载供应商表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载供应商表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportSyssupplierOutput>(), "供应商表导入模板");
    }
    
    private static readonly object _syssupplierImportLock = new object();
    /// <summary>
    /// 导入供应商表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入供应商表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (_syssupplierImportLock)
        {
            var stream = ExcelHelper.ImportData<ImportSyssupplierInput, Syssupplier>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Status == null){
                            x.Error = "状态不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Syssupplier>>();
                    
                    var storageable = _syssupplierRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Code), "供应商编码不能为空")
                        .SplitError(it => it.Item.Code?.Length > 50, "供应商编码长度不能超过50个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Name), "供应商名称不能为空")
                        .SplitError(it => it.Item.Name?.Length > 100, "供应商名称长度不能超过100个字符")
                        .SplitError(it => it.Item.Industry?.Length > 50, "所属行业长度不能超过50个字符")
                        .SplitError(it => it.Item.Category?.Length > 50, "供应商分类长度不能超过50个字符")
                        .SplitError(it => it.Item.ContactPerson?.Length > 50, "联系人长度不能超过50个字符")
                        .SplitError(it => it.Item.ContactPhone?.Length > 20, "联系电话长度不能超过20个字符")
                        .SplitError(it => it.Item.Email?.Length > 100, "电子邮箱长度不能超过100个字符")
                        .SplitError(it => it.Item.PurchasingDepartment?.Length > 50, "进货部门长度不能超过50个字符")
                        .SplitError(it => it.Item.PurchasingManager?.Length > 50, "进货负责人长度不能超过50个字符")
                        .SplitError(it => it.Item.Address?.Length > 200, "供应商地址长度不能超过200个字符")
                        .SplitError(it => it.Item.Remarks?.Length > 255, "备注长度不能超过255个字符")
                        .SplitError(it => it.Item.AccountName?.Length > 100, "账户名称长度不能超过100个字符")
                        .SplitError(it => it.Item.TaxpayerId?.Length > 50, "纳税人识别号长度不能超过50个字符")
                        .SplitError(it => it.Item.BankAccount?.Length > 50, "银行账户长度不能超过50个字符")
                        .SplitError(it => it.Item.OpeningBank?.Length > 100, "开户银行长度不能超过100个字符")
                        .SplitError(it => it.Item.OpeningBankAddress?.Length > 200, "开户行地址长度不能超过200个字符")
                        .SplitInsert(_=> true) // 没有设置唯一键代表插入所有数据
                        .ToStorage();
                    
                    storageable.AsInsertable.ExecuteCommand();// 不存在插入
                    storageable.AsUpdateable.UpdateColumns(it => new
                    {
                        it.Code,
                        it.Name,
                        it.Industry,
                        it.Category,
                        it.ContactPerson,
                        it.ContactPhone,
                        it.Email,
                        it.PurchasingDepartmentId,
                        it.PurchasingDepartment,
                        it.PurchasingManagerId,
                        it.PurchasingManager,
                        it.Status,
                        it.Address,
                        it.Remarks,
                        it.AccountName,
                        it.TaxpayerId,
                        it.BankAccount,
                        it.OpeningBank,
                        it.OpeningBankAddress,
                        it.DeleteTime,
                    }).ExecuteCommand();// 存在更新
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
